<?php

namespace apiend\modules\mall\controllers;

use Yii;
use apiend\components\Controller;
use common\models\shop\ShopCart;
use apiend\modules\mall\models\CartSearch;
use apiend\modules\mall\models\CartPackBalanceForm;
use apiend\modules\mall\models\CartUpdateForm;
use apiend\modules\mall\models\CartDeleteForm;
use apiend\modules\mall\models\CartCollectForm;

/**
 * 购物车相关接口
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartController extends Controller {

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            'index' => ['GET'],
            'number' => ['GET'],
            '*' => ['POST'],
        ];
    }

    /**
     * 购物车列表
     * @return mixed
     */
    public function actionIndex() {
        $user_id = $this->uid;
        ShopCart::updateAll(['status' => ShopCart::STATUS_CHECKED], [
            'user_id' => $user_id,
            'status' => ShopCart::STATUS_PREPARE_ORDER
        ]);
        /* @var $model \apiend\modules\mall\models\CartSearch */
        $model = new CartSearch();
        $model->user_id = $user_id;
        return $model->search();
    }

    /**
     * 购物车单条数量更新
     * @return array
     */
    public function actionUpdate() {
        $model = new CartUpdateForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->dumpError('加入购物车失败');
        }
        return $model->save();
    }

    /**
     * 获取当前购物车最新数量
     * @return integer
     */
    public function actionNumber() {
        $model = new CartSearch();
        $model->user_id = $this->uid;
        $amount = $model->buildQuery()->groupBy('t.product_id')->count();
        return intval($amount);
    }

    /**
     * 结算提交保存
     * @return integer
     */
    public function actionBalance() {
        $model = new CartPackBalanceForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->dumpError('购物车商品结算提交失败');
        }
        $model->user_id = $this->uid;
        return $model->save();
    }

    /**
     * 批量删除购物车商品
     */
    public function actionDelete() {
        $model = new CartDeleteForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->dumpError('购物车内容删除失败');
        }
        $model->user_id = $this->uid;
        return $model->save();
    }

    /**
     * 批量收藏购物车商品
     */
    public function actionCollect() {
        $model = new CartCollectForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->dumpError('购物车商品收藏失败');
        }
        $model->user_id = $this->uid;
        return $model->save();
    }

}
